import { ref,computed } from 'vue'
import { defineStore } from 'pinia'
import {getAddCartAPI,getCartListAPI,getRemoveCartAPI,updateCarNumAPI,selectAllAPI,selectOneAPI} from '@/API/goods'
import {deleteCartItemAPI} from '@/API/order'
import {useUserStore} from '@/stores/user'


export const useGoodsStore = defineStore('goods', () => {
  const goodsList = ref<any[]>([])
  const userStore = useUserStore()
 

  //购物车列表
  const getGoodsList =async ()=>{
   const res=await getCartListAPI(userStore.info.userid)
   console.log(res);
   
   goodsList.value=res.data
  }


  //加入购物车
  const addGoodsList =async (goods:any) =>{
    console.log(goods);
    
    const item:any=goodsList.value.find((item:any) => item.proid===goods.proid)
    if(item){
      item.discount++
    }else{
      goodsList.value.push(goods)
    }
    //加入购物车接口
   await getAddCartAPI(userStore.info.userid,goods.proid,goods.discount)
   //更新本地购物车
   getGoodsList()
   
  }

  //删除购物车数据

  const delGoodsList =async(cartid:any)=>{
    console.log(cartid);
    
    goodsList.value= goodsList.value.filter(item=>item.cartid!==cartid)

    await getRemoveCartAPI(cartid)
   
   
    getGoodsList()
  }
   
   //更新购物车数量
   const updateCarNum =async(cartid:any,num:any)=>{
      await updateCarNumAPI(cartid,num)
   }



   
  //总金额
  
  const total=computed(()=>goodsList.value.filter(item=>item.flag).reduce((sum,item)=>sum+item.discount*item.originprice,0))
    // if(goodsList.value){
     
    // }
  
  
  //计算是否全选
  const all = computed(()=>goodsList.value.every(item=>item.flag))
  
 
    

    
      
  
  //点击全选改变所有状态
  const isChangeAll = async(flag:any)=>{
   
    goodsList.value.forEach(item=>item.flag=flag)

    await selectAllAPI(userStore.info.userid,flag)
  }

  //更新当前购物车数据的选中状态
  const selectOne = async(cartid:any,flag:any)=>{

   await selectOneAPI(cartid,flag)
  }
//支付时删除购物车选中的数据
  const deleteCartItem=async()=>{
   await deleteCartItemAPI(userStore.info.userid)
   getGoodsList()

  }


  return {
    goodsList,
    addGoodsList,
    delGoodsList,
    total,
    all,
    // updateSelected
    isChangeAll,
    getGoodsList,
    updateCarNum,
    selectOne,
    deleteCartItem
   }
   
},
{
  persist: true,
}
)
